from rest_framework import serializers

from .models import *


class ControlMenuSer(serializers.ModelSerializer):
    class Meta:
        model = ControlMenu
        fields = "__all__"


class RoleControlMenuSer(serializers.ModelSerializer):
    control = ControlMenuSer()

    class Meta:
        model = RoleControlMenu
        fields = "__all__"


class RoleControlMenuListSer(serializers.ModelSerializer):
    control = ControlMenuSer()
    children = serializers.SerializerMethodField()

    def get_children(self, obj):
        # 根据父的ID 查询出 所有的二级菜单
        sub_list = ControlMenu.objects.filter(parent_id=obj.control.id).values_list("id")
        sub_queryset = RoleControlMenu.objects.filter(role_id=obj.role.id, control_id__in=sub_list)

        return RoleControlMenuSer(sub_queryset, many=True).data

    class Meta:
        model = RoleControlMenu
        fields = "__all__"


class RoleSer(serializers.ModelSerializer):
    class Meta:
        model = Role
        fields = "__all__"
